import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:get/get.dart';

import 'state.dart';

class SearchLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final state = SearchState();

  @override
  void onInit() {
    state.tabController =
        TabController(length: state.category.length, vsync: this);
    super.onInit();
  }

  fetchList() async {
    if (state.keyword.isEmpty) {
      state.category[state.currentIndex]['list'].clear();
    } else {
      var res = await Http.instance.post(
          '/plugin/search/api/${state.result['type'] == 'all' ? 'all' : 'multiple'}',
          data: {
            "keyword": state.keyword,
            "page": state.pagination.currentPage,
            "type": state.result['type'],
          });

      if (res.code == 1) {
        if (state.result['type'] == 'all') {
          state.category[state.currentIndex]['list'] = res.data;
        } else {
          if (state.pagination.currentPage == 1) {
            state.category[state.currentIndex]['list'].clear();
          }
          state.pagination = ListPaginationModel.fromJson(res.data);
          res.data['data'].forEach((item) {
            state.category[state.currentIndex]['list'].add(item);
          });
          state.refreshController.finishLoad();
        }
      }
    }
    state.loading = false;
    update(['result']);
  }

  onTabsClick(index) {
    state.currentIndex = index;
    state.pagination.currentPage = 1;
    if (state.keyword.isNotEmpty) {
      state.loading = true;
      update(['result']);
    }
    state.searchBarController.unfocus();
    fetchList();
  }

  search(keyword) {
    state.keyword = keyword;
    state.pagination.currentPage = 1;
    state.loading = true;
    update(['result']);
    fetchList();
  }
}
